import Vue from 'vue';
import Router from 'vue-router';
import iView from 'iview';

Vue.use(Router);

const router = new Router({
    mode: 'history',
    base: __dirname
});

router.beforeEach((to, from, next) => {
    //console.log('beforeEach');
    iView.LoadingBar.start();
    next();
});

router.afterEach((route) => {
    //console.log('afterEach');
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});

router.onReady(callback => {
    console.log('onReady');
});

router.onError((callback) => {
    console.log('onError');
});

//路由去中心化
let routes = [];
let routerObj = {};
let routerChildrenObj = {}; 
const routerContext = require.context('../views/', true, /router\.js$/)
routerContext.keys().map(function(key){
    //console.log(38,key,routerContext(key));
    if (routerContext(key).default) {
        checkChildren(key);
    } else {
        console.log('the path '+key+'  is error');
    }
});

//提取二级目录路由
function checkChildren(key) {
   let routerModuleObj = routerContext(key).default;
   if (routerModuleObj.children) {
        let arr = routerChildrenObj[routerModuleObj.name];
        if (!arr) { 
            arr = [];
        }
        arr = arr.concat(routerModuleObj.children);
        routerChildrenObj[routerModuleObj.name] = arr;
        //console.log(56,key,routerModuleObj,arr);
   } else {
        routerObj[routerModuleObj.name] = routerContext(key).default;
   }
}

//组装二级目录
for (var i in routerChildrenObj) {
    //console.log(63,i,routerObj,routerChildrenObj);
    routerObj[i].children = routerChildrenObj[i];
}

//对象路由转标准数组路由
for (var j in routerObj) {
    routes.push(routerObj[j]);
}

//console.log('router',routerObj,routes);
router.addRoutes(routes);

export default router;